<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>HTML5 history pushState/replaceState</title>
</head>

<body>
    <a href="./hash2.html">实例二</a>
    <a href="../../../index.html">返回</a>
    <hr>
    <button id="a">A</button>
    <button id="b">B</button>
    <button id="c">C</button>
    <div id="cont"></div>
    <script>
        let cont = document.querySelector("#cont")
        let a = document.getElementById("a")
        let b = document.getElementById("b")
        let c = document.getElementById("c")
        let h = location.href
        a.onclick = function () {
            getSearch(this)
            console.log(history.state);
        }
        b.onclick = function () {
            getSearch(this)
            console.log(history.state);
        }
        c.onclick = function () {
            getSearch(this)
            console.log(history.state);
        }
        function getSearch(e) {
            history.pushState(e.innerHTML, document.title, location.href.split("?")[0] + "?" + e.innerHTML)
            let search = location.href.split("?")[1]
            cont.innerHTML = location.href
            return search
        }
        
        function loadHash() {
            console.log(history.state);
            if (!history.state) {
                if (location.href.indexOf("?") != -1) {
                    history.replaceState(null, document.title, "?" + location.href.split("?")[1])
                } else {
                    history.replaceState(null, document.title, "?A")
                }
            } else {
                history.replaceState(history.state, document.title, "?" + history.state)
            }
            cont.innerHTML = location.href
            // console.log(history.state);
        }
        loadHash()
        window.addEventListener("popstate", loadHash)
    </script>
</body>

</html>